﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace FourKillEnginePrototype
{
    public static class ObjectParser3D
    {
        public static List<Polygon3D> ParseWavefrontObject(string path)
        {

            // This is my attempt at parsing a wave front object.
            // It reads the faces and the vertices.
            // I haven't taken into account textures or anything yet.
            List<Point3D> points = new List<Point3D>();
            List<Polygon3D> polygons = new List<Polygon3D>();
            using (StreamReader sr = new StreamReader(path)) 
            {
                while (sr.Peek() >= 0) 
                {
                    string line = sr.ReadLine();
                    if (line != String.Empty && line.Substring(0, 1) == "v")
                    {
                        var verticies = line.Split(' ');
                        Point3D p3d = new Point3D(Convert.ToDouble(verticies[1]), Convert.ToDouble(verticies[2]), Convert.ToDouble(verticies[3]));
                        points.Add(p3d);
                    } else if(line.StartsWith("f"))
                    {
                        var faces = line.Split(' ');
                        var poly = new Polygon3D();
                        for (int i = 1; i < faces.Length; i++)
                        {
                            int v = Convert.ToInt32(faces[i]);
                            Point3D vert = new Point3D(points[v-1].X, points[v-1].Y, points[v-1].Z);
                            poly.Points.Add(vert);
                        }
                        polygons.Add(poly);
                    }
                }
            }
            return polygons;
        }

    }
}
